package priv.wangy.micro.common.po.page;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.SuperBuilder;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangjq
 * @since 2024-05-27
 */
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public class MongoPage<T> extends PageHelper<T> {

    /**
     * 执行分页并排序
     * 每页显示的数据条数与当前页码有一个不大于0时，使用默认分页条件
     * 默认分页条件：
     * 每页显示的数据条数 10
     * 当前页码 1
     */
    public void paging(Query query) {
        long skip;
        int limit;
        if (Objects.isNull(this.getPage()) || this.getPage().getPageNum() <= 0 || this.getPage().getPageSize() <= 0) {
            skip = 0;
            limit = 10;
        } else {
            skip = (long) (this.getPage().getPageNum() - 1) * this.getPage().getPageSize();
            limit = this.getPage().getPageSize();
        }
        query.skip(skip);
        query.limit(limit);
        sorting(query);
    }

    /**
     * 执行排序
     */
    public void sorting(Query query) {
        if (!CollectionUtils.isEmpty(this.getSorts())) {
            List<Sort.Order> orderList = new ArrayList<>();
            for (SortCriteria sort : this.getSorts()) {
                if (StringUtils.hasLength(sort.getProperty()) && StringUtils.hasLength(sort.getOrder())) {
                    if (SortCriteria.Order.ASC.equals(sort.getOrder())) {
                        orderList.add(Sort.Order.asc(sort.getProperty()));
                    } else if (SortCriteria.Order.DESC.equals(sort.getOrder())) {
                        orderList.add(Sort.Order.desc(sort.getProperty()));
                    }
                }
            }
            query.with(Sort.by(orderList.toArray(Sort.Order[]::new)));
        }
    }
}
